import { Avatar, Card, Divider, List, Radio, Select,Button, Form, Input, Modal, message, Row, Col, Icon } from "antd";
import { formatMessage } from 'umi-plugin-react/locale';
import React from "react";
import styles from "./index.less"
import ConfigEdit from "./configEdit";
import { configurationBaseDetail, configurationBaseEdit, configurationDelete, configurationEdit, configurationList, configurationStatusEdit } from "@/services/workOrder";
import UserSession from "@/UserSession";
import tableDataCheck from "@/utils/isBackPrevPage";
import { adminList } from "@/services/userProfile";

class PolicyConfiguration extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      userList:[],
      list: [],
      total: 0,
      current: 1,
      size: 15,
      loading: false,
      id:""
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
    if(UserSession.getCurrentUser().isAdmin){
      //甲方管理员
      this.getDetail()
      this.getUserList()
    }else{
      //乙方
      this.getList()
    }
    
  }

  getDetail = async () => {
    const res = await configurationBaseDetail({applicationId:UserSession.getCurrentUser().applicationId})
    this.props.form.setFieldsValue({type:res.type})
    if(res.type != 0){
      this.props.form.setFieldsValue({headerIds:res.headerIds})
    }
    if(res.type == 2){
      this.props.form.setFieldsValue({relUserIds:res.relUserIds})
    }
    if(res.type == 3){
      this.getList()
    }
    this.setState({id:res.id})
  }

  getList = () => {
    this.setState({
      loading:true
    },async () => {
      const { current,size } = this.state;
      const formInfo = this.props.form.getFieldsValue()
      let obj = {
        search:formInfo.search,
        status:formInfo.status,
        current,
        size,
        applicationId:UserSession.getCurrentUser().applicationId,
        orderFlag:UserSession.getCurrentUser.isAdmin ? 0 : 1
      }
      const res = await configurationList(obj)
      this.setState({
        loading:false,
        list:res.records,
        total:res.total
      })
    })
  }

  changePage = (current,size) => {
    this.setState({
      current,size
    },this.getList())
  }

  handleDelete = (id) => {
    const that = this;
    Modal.confirm({
      title: formatMessage({ id: 'pages.workOrder.policyConfiguration.message.deleteConfirm' }),
      okText: formatMessage({ id: 'pages.workOrder.policyConfiguration.message.ok' }),
      cancelText: formatMessage({ id: 'pages.workOrder.policyConfiguration.message.cancel' }),
      okType:"danger",
      onOk(){
        that.doDelete(id)
      }
    })
  }

  doDelete = async (id) => {
    const res = await configurationDelete({id})
    message.info(res.message)
    const { current, size, list } = this.state;
    const newCurrent = tableDataCheck(list, current)
    this.changePage(newCurrent, size)
  }

  handleStatus = async (id,status) => {
    const res = await configurationStatusEdit({id,status})
    message.info(res.message)
    this.getList()
  }

  addRule = () => {
    this.ConfigEdit.initData()
  }

  handleEdit = id => {
    this.ConfigEdit.initData(id)
  }

  getUserList = async () => {
    const res = await adminList({current:1,size:999999,applicationId:UserSession.getCurrentUser().applicationId})
    this.setState({userList:res.records})
  }

  configurationValidate = () => {
    this.props.form.validateFields((error,values) => {
      if(!error){
        this.doSave(values)
      }
    })
  }

  doSave = async values => {
    const { id } = this.state;
    const res = await configurationBaseEdit({...values,applicationId:UserSession.getCurrentUser().applicationId,id})
    message.info(res.message)
  }

  changeType = e => {
    if(e.target.value == 3){
      this.getList()
    }
  }

  render(){
    const { userList,list,total,current,size,loading } = this.state;
    const { form:{getFieldDecorator,getFieldValue} } = this.props;
    return(
      <Card style={{height:"100%"}} bordered={false}>
      <Form layout="inline" style={{marginBottom:20}} className="configuration">
        {
          UserSession.getCurrentUser().isAdmin ? (
            <div>
              <Form.Item label={formatMessage({ id: 'pages.workOrder.policyConfiguration.label.policyConfig' })} style={{display:"block"}} >
              {getFieldDecorator("type")(
                <Radio.Group onChange={this.changeType}>
                  <Radio value={0}>
                    {formatMessage({ id: 'pages.workOrder.policyConfiguration.radio.disableSubmit' })}
                  </Radio>
                  <Radio value={1}>
                    {formatMessage({ id: 'pages.workOrder.policyConfiguration.radio.serviceHandleAll' })}
                  </Radio>
                  <Radio value={2}>
                    {formatMessage({ id: 'pages.workOrder.policyConfiguration.radio.companyHandleAll' })}
                  </Radio>
                  <Radio value={3}>
                    {formatMessage({ id: 'pages.workOrder.policyConfiguration.radio.customRule' })}
                  </Radio>
                </Radio.Group>
              )}
            </Form.Item>
            {
              getFieldValue("type") != 0 ? (
                <Form.Item label={formatMessage({ id: 'pages.workOrder.policyConfiguration.label.responsiblePerson' })} style={{display:"block"}}>
                  {getFieldDecorator("headerIds",{rules:[{required:true,message:formatMessage({ id: 'pages.workOrder.policyConfiguration.message.pleaseSelect' })}]})(
                    <Select style={{width:400}} mode="multiple" >
                      {
                        userList.map(item => {
                          return (
                            <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                          )
                        })
                      }
                    </Select>
                  )}
                </Form.Item>
              ) : ''
            }
            {
              getFieldValue("type") == 2 ? (
                <Form.Item label={formatMessage({ id: 'pages.workOrder.policyConfiguration.label.handler' })} style={{display:"block"}}>
                  {getFieldDecorator("relUserIds",{rules:[{required:true,message:formatMessage({ id: 'pages.workOrder.policyConfiguration.message.pleaseSelect' })}]})(
                    <Select style={{width:400}} mode="multiple" >
                      {
                        userList.map(item => {
                          return (
                            <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                          )
                        })
                      }
                    </Select>
                  )}
                </Form.Item>
              ) : ''
            }
            <Form.Item><Button type="primary" onClick={this.configurationValidate} style={{marginLeft:70,marginTop:15}}>
              {formatMessage({ id: 'pages.workOrder.policyConfiguration.button.save' })}
            </Button></Form.Item>
            <Divider />
            </div>
          ) : ''
        }
        {
          getFieldValue("type") == 3 || !UserSession.getCurrentUser().isAdmin ? (
            <div>
              <div style={{marginBottom:20}}>
                <Form.Item>
                    {getFieldDecorator("status")(
                      <Select style={{width:150}} placeholder={formatMessage({ id: 'pages.workOrder.policyConfiguration.label.status' })}>
                        <Select.Option value={null}>{formatMessage({ id: 'pages.workOrder.policyConfiguration.status.all' })}</Select.Option>
                        <Select.Option value={0}>{formatMessage({ id: 'pages.workOrder.policyConfiguration.status.disabled' })}</Select.Option>
                        <Select.Option value={1}>{formatMessage({ id: 'pages.workOrder.policyConfiguration.status.enabled' })}</Select.Option>
                      </Select>
                    )}
                  </Form.Item>
                  <Form.Item>
                    {getFieldDecorator("search")(<Input.Search placeholder={formatMessage({ id: 'pages.workOrder.policyConfiguration.label.search' })} onSearch={() => this.changePage(1,size)} />)}
                  </Form.Item>
                  <Form.Item><Button onClick={() => this.changePage(1,size)} type="primary">
                    {formatMessage({ id: 'pages.workOrder.policyConfiguration.button.search' })}
                  </Button></Form.Item>
              </div>
              <List
                rowKey="id"
                loading={loading}
                pagination={{
                  onChange: this.changePage,
                  pageSize: 16,
                  total: total + 1,
                  showQuickJumper: true,
                }}
                grid={{ gutter: 16, column: 4 }}
                dataSource={["", ...list]}
                renderItem={(item) =>
                  item ? (
                    <List.Item key={item.id}>
                      <Card
                        hoverable
                        className={styles.card}
                        actions={[
                          <a onClick={() => this.handleDelete(item.id)}>
                            {formatMessage({ id: 'pages.workOrder.policyConfiguration.button.delete' })}
                          </a>,
                          <a onClick={() => this.handleEdit(item.id)}>
                            {formatMessage({ id: 'pages.workOrder.policyConfiguration.button.edit' })}
                          </a>,
                          item.status == 0 ? 
                            <a onClick={() => this.handleStatus(item.id,1)}>
                              {formatMessage({ id: 'pages.workOrder.policyConfiguration.button.enable' })}
                            </a> : 
                            <a onClick={() => this.handleStatus(item.id,0)}>
                              {formatMessage({ id: 'pages.workOrder.policyConfiguration.button.disable' })}
                            </a> 
                        ]}
                        bodyStyle={{height:120}}
                      >
                        <Card.Meta
                          avatar={
                            <Avatar className={styles.cardAvatar}>
                              {item.ruleName.substr(0, 1)}{" "}
                            </Avatar>
                          }
                          title={
                            <a
                              title={item.ruleName}
                              style={{
                                width: "100%",
                                display: "block",
                                overflow: "hidden",
                                whiteSpace: "nowrap",
                                textOverflow: "ellipsis",
                                color: "#000000",
                              }}
                            >
                              {item.ruleName}
                            </a>
                          }
                          description={
                            <div>
                              <div style={{
                                overflow: "hidden",
                                whiteSpace: "nowrap",
                                textOverflow: "ellipsis",
                              }}>{formatMessage({ id: 'pages.workOrder.policyConfiguration.label.assigner' })}：{item.relUserNames ? formatMessage({ id: 'pages.workOrder.policyConfiguration.label.company' }) : formatMessage({ id: 'pages.workOrder.policyConfiguration.label.service' })}</div>
                              {
                                item.relUserNames ? (
                                  <div style={{
                                    overflow: "hidden",
                                    whiteSpace: "nowrap",
                                    textOverflow: "ellipsis",
                                  }}>{formatMessage({ id: 'pages.workOrder.policyConfiguration.label.handler' })}：{item.relUserNames}</div>
                                ) : ''
                              }
                              {
                                item.status == 0 ? <div style={{color:"#f5222d"}}><Icon type="pause-circle" style={{marginRight:5}} />{formatMessage({ id: 'pages.workOrder.policyConfiguration.status.disabled' })}</div> : ''
                              }
                              <div></div>
                            </div>
                          }
                        />
                      </Card>
                    </List.Item>
                  ) : (
                    <List.Item>
                      <Button
                        type="dashed"
                        htmlType="button"
                        className={styles.newButton}
                        onClick={this.addRule}
                      >
                        {formatMessage({ id: 'pages.workOrder.policyConfiguration.button.add' })}
                      </Button>
                    </List.Item>
                  )
                }
              />
            </div>
          ) : ''
        }
        </Form>
        <ConfigEdit onRef={ref => this.ConfigEdit = ref} refreshList={() => this.changePage(1,size)} />
      </Card>
    )
  }
}

export default Form.create()(PolicyConfiguration)